import { DownloadOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import moment from 'moment';
import type { ReactNode} from 'react';
import React, { useEffect, useState } from 'react';
import type { exportType } from './service';
import { exportMap } from './service';
interface downProps {
  data: Object;
  fileName?: string;
  hideTime?: boolean;
  type: exportType;
  customFileName?: string;
  fileType: string;
  label?: string;
  render?: ReactNode;
  disabled?: boolean;
  beforeDownload?: () => boolean;
}

export const downloadFile = (filename: any, fileUrl: any, type: any) => {
  // const token = localStorage.getItem('token'); //
  const xhr = new XMLHttpRequest();
  const url = fileUrl; //请求的api
  xhr.open('get', url, true);
  xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem('auth-token')}`); // 给后端发送请求头
  xhr.responseType = 'blob';
  xhr.onload = function (e) {
    if (this.status === 200) {
      const blob = this.response;
      const urlObject = window.URL || window.webkitURL || window;
      const export_blob = new Blob([blob]);
      const a = document.createElement('a'); // 利用a标签特性下载
      const url = urlObject.createObjectURL(export_blob);
      a.href = url;
      if (filename.indexOf('.sgf') > 0) {
        a.download = filename;
      } else {
        a.download = filename + '.' + type;
      }
      a.click();
    }
  };
  xhr.send();
};

const ExportButton: React.FC<downProps> = (props) => {
  const {
    data,
    fileName,
    hideTime = false,
    type,
    customFileName,
    fileType,
    label = '导出',
    render,
    disabled = false,
    beforeDownload = () => {
      return true;
    },
  } = props;

  const [params, setParams] = useState(data);
  useEffect(() => {
    if (data) {
      setParams({ ...data });
    }
  }, [data]);
  const downloadFileHandler = async () => {
    for (const k in params) {
      if (!params[k]) {
        delete params[k];
      }
    }
    const url = await exportMap[type](params);

    //优先采用customFileName

    const name = customFileName
      ? customFileName
      : !hideTime
      ? `${fileName}_${moment().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss')}`
      : fileName;
    downloadFile(name, url, fileType);
  };
  return render ? (
    <a
      onClick={() => {
        beforeDownload() && downloadFileHandler();
      }}
    >
      {render}
    </a>
  ) : (
    <Button
      type="primary"
      onClick={() => {
        beforeDownload() && downloadFileHandler();
      }}
      disabled={disabled}
    >
      <DownloadOutlined />
      {label}
    </Button>
  );
};

export default ExportButton;
